// miniprogram/pages/signUpRecord/signUpRecord.js

import Encoder from "../../utils/Encoder";
import Decoder from "../../utils/Decoder";

//实现参考例子
// var message = "减肥是一件困难的事情";

// //UTF-8转GBK
// var gbkArray = Encoder.hexstrToArray(Encoder.stringToGbkHexstr(message));
// console.log("gbkArray>>" + gbkArray);
// //GBK转UTF-8
// var utfStr = Decoder.GBKHexstrToString(Decoder.binaryarrayToHexstr(gbkArray));
// console.log("utfStr>>" + utfStr);

Page({

  /**
   * 页面的初始数据
   */
  data: {
    signUpList: [],
    batchIds: [],   // 选中的ID
    select_all: false,
    select_anti: false,
    gameId: "",

    select_unknown: false,
    select_success: false,
    select_fail: false,
  },

  //全选
  selectAll: function () {
    var that = this;
    var arr = [];   //存放选中id的数组
    for (let i = 0; i < that.data.signUpList.length; i++) {
      that.data.signUpList[i].checked = (!that.data.select_all)
      arr.push(that.data.signUpList[i]._id)
    }
    // console.log(arr)
    that.setData({
      signUpList: that.data.signUpList, // 保证更新
      select_all: (!that.data.select_all),
      batchIds: arr
    })
  },

  // 反选
  selectAnti: function () {
    var that = this;
    var arr = [];   //存放选中id的数组
    for (let i = 0; i < that.data.signUpList.length; i++) {
      that.data.signUpList[i].checked = (!that.data.signUpList[i].checked)
      if (that.data.signUpList[i].checked == true) {
        // 全选获取选中的值
        arr.push(that.data.signUpList[i]._id)
      }
    }
    // console.log(arr)
    that.setData({
      signUpList: that.data.signUpList, // 保证更新
      batchIds: arr
    })

    // 修改全选框
    if (that.data.signUpList.length != that.data.batchIds.length) {
      that.setData({
        select_all: false
      })
    } else {
      that.setData({
        select_all: true
      })
    }
  },

  // 单选
  checkboxChange: function (e) {
    this.setData({
      batchIds: e.detail.value  //单个选中的值
    })
    // console.log(this.data.batchIds)
  },

  // 修改单选的checked
  setChecked: function (e) {
    // console.log(e)
    let that = this
    for (let i = 0; i < that.data.signUpList.length; i++) {
      if (that.data.signUpList[i]._id == e.currentTarget.dataset.id) {
        that.data.signUpList[i].checked = (!that.data.signUpList[i].checked)
        if (that.data.signUpList[i].checked == false) {
          that.setData({
            select_all: false
          })
        }
        break;
      }
    }

    if (that.data.signUpList.length != that.data.batchIds.length) {
      that.setData({
        select_all: false
      })
    } else {
      that.setData({
        select_all: true
      })
    }
  },

  // 点击状态、组别、姓名、城市、学校、导师、考号等按对应属性排序
  // 状态排序-begin
  orderByState: function (e) {
    console.log("根据状态排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compState)
    })
  },

  compState: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.state)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.state)))
      return 1
    else
      return -1
  },
  // 状态排序-end

  // 组别排序-begin
  orderByGroup: function (e) {
    console.log("根据组别排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compGroup)
    })
  },

  compGroup: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.group)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.group)))
      return 1
    else
      return -1
  },
  // 组别排序-end

  // 姓名排序-begin
  orderByName: function (e) {
    console.log("根据姓名排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compName)
    })
  },

  compName: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.name)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.name)))
      return 1
    else
      return -1
  },
  // 姓名排序-end

  // 城市排序-begin
  orderByCity: function (e) {
    console.log("根据城市排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compCity)
    })
  },

  compCity: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.city)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.city)))
      return 1
    else
      return -1
  },
  // 城市排序-end

  // 学校排序-begin
  orderBySchool: function (e) {
    console.log("根据学校排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compSchool)
    })
  },

  compSchool: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.school)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.school)))
      return 1
    else
      return -1
  },
  // 学校排序-end

  // 导师排序-begin
  orderByTutor: function (e) {
    console.log("根据导师排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compTutor)
    })
  },

  compTutor: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.tutor)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.tutor)))
      return 1
    else
      return -1
  },
  // 导师排序-end

  // 考号排序-begin
  orderByNumber: function (e) {
    console.log("根据考号排序")
    var arr = this.data.signUpList;
    this.setData({
      signUpList: arr.sort(this.compNumber)
    })
  },

  compNumber: function (a, b) {
    if (a.contestant_id >= b.contestant_id)
      return 1
    else
      return -1
  },
  // 考号排序-end
  // 排序-end

  // 点击编号给报名成功的人编号（即考号）
  setOrder: function() {
    // 方法1：用promise解决异步处理问题
    let that = this
    wx.showToast({
      title: '开始编号',
    })

    let arr = []
    let PromiseArr = []
    for (let i = 0; i < that.data.batchIds.length; ++i) {
      PromiseArr.push(new Promise((resolve, reject) => {
        wx.cloud.callFunction({
          name: "getSignUpRecordBySignUpId",
          data: {
            _id: that.data.batchIds[i]
          },
          success: res => {
            console.log('根据_id获取报名信息成功', res)
            resolve(res)
            arr.push(res.result.data[0])
          },
          fail: err => {
            console.log('根据_id获取报名信息失败', err)
            reject(err)
          },
        })
      }))
    }

    Promise.all(PromiseArr).then(res => {
      // 获取当前最大考号
      let tempArr = that.data.signUpList.sort(that.compNumber)
      // console.log(tempArr[that.data.signUpList.length - 1], "---------------")
      let baseString = tempArr[that.data.signUpList.length - 1].contestant_id
      let baseNum = parseInt(baseString.substring(3))
      if (baseString == "")
        baseNum = 0

      wx.showToast({
        title: '将从' + (baseNum + 1) + '开始编号',
        image: "/images/loading.png",
        duration: 3000,
      })
      // console.log(baseString, baseString.substring(3), baseNum)

      // console.log(that.data.chooseArr)
      arr = arr.sort(that.compSchool)
      arr = arr.sort(that.compCity)

      for (let i = 0; i < arr.length; ++i) {
        // console.log(arr[i].user.city, arr[i].user.school)
        let tempNumber = baseNum + i + 1
        let tempString = tempNumber.toString()
        while (tempString.length < 4) {
          tempString = "0" + tempString
        }
        // console.log(tempString)
        arr[i].contestant_id = "GD-" + tempString
        // console.log(res.result.data[i].contestant_id)

        wx.cloud.callFunction({
          name: "updateNumber",
          data: {
            _id: arr[i]._id,
            contestant_id: arr[i].contestant_id
          },
          success: res => {
            console.log('编号成功', res)
          },
          fail: res => {
            console.log('编号失败', res)
          },
        })
      }

      setTimeout(function () {
        that.onReady()
        wx.showToast({
          title: '编号完成',
        })
      }, 3000)
    }, err => {
      console.log(err)
    })


    // 方法2：用延时解决异步处理问题
    // let that = this
    // wx.showToast({
    //   title: '开始编号',
    // })

    // let arr = []
    // for (let i = 0; i < that.data.batchIds.length; ++i) {
    //   wx.cloud.callFunction({
    //     name: "getSignUpRecordBySignUpId",
    //     data: {
    //       _id: that.data.batchIds[i]
    //     },
    //     success: res => {
    //       console.log('根据_id获取报名信息成功', res)
    //       arr.push(res.result.data[0])
    //       // console.log(arr)
    //       that.setData({
    //         chooseArr: arr
    //       })
    //       // console.log(that.data.chooseArr)
    //     },
    //     fail: res => {
    //       console.log('根据_id获取报名信息失败', res)
    //     },
    //   })
    // }

    // // 等待足够的时间以便异步获取选中的报名信息
    // setTimeout(function() {
    //   // console.log(that.data.chooseArr)
    //   // 对arr进行重新排序
      // arr = arr.sort(that.compSchool)
      // arr = arr.sort(that.compCity)

      // for (let i = 0; i < arr.length; ++i) {
      //   // console.log(arr[i].user.city, arr[i].user.school)
      //   let tempNumber = i + 1
      //   let tempString = tempNumber.toString()
      //   while (tempString.length < 4) {
      //     tempString = "0" + tempString
      //   }
      //   // console.log(tempString)
      //   arr[i].contestant_id = "GD-" + tempString
      //   // console.log(res.result.data[i].contestant_id)

      //   wx.cloud.callFunction({
      //     name: "updateNumber",
      //     data: {
      //       _id: arr[i]._id,
      //       contestant_id: arr[i].contestant_id
      //     },
      //     success: res => {
      //       console.log('编号成功', res)
      //     },
      //     fail: res => {
      //       console.log('编号失败', res)
      //     },
      //   })
      // }

      // setTimeout(function () {
      //   that.onReady()
      //   wx.showToast({
      //     title: '编号完成',
      //   })
      // }, 3000)
    // }, 5000)
  },

  compSchool: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.school)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.school)))
      return 1
    else
      return -1
  },

  compCity: function (a, b) {
    if (Encoder.hexstrToArray(Encoder.stringToGbkHexstr(a.user.city)) >= Encoder.hexstrToArray(Encoder.stringToGbkHexstr(b.user.city)))
      return 1
    else
      return -1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    that.setData({
      gameId: options._id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 获取报名列表
    let that = this
    wx.cloud.callFunction({
      name: "getSignUpListByGameIdAndState",
      data: {
        gameId: that.data.gameId,
        state: "成功"
      },
      success: res => {
        console.log("调用云函数获取报名列表成功", res)

        that.setData({
          signUpList: res.result.data,
          batchIds: [],
          select_all: false,
        })
      },
      fail: res => {
        console.log("调用云函数获取报名列表失败", res)
      }
    })
    wx.showToast({
      title: '加载完成',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})